package com.stock.db;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;

import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;

public abstract class BaseDAO {
	// private final String driver = "com.mysql.jdbc.Driver";
    //private final String url = "jdbc:mysql://localhost:3306/stock";
    private static final String servierName="localhost";
    private static final String dateTableName="stock";
	private static final String usr = "stock";
    private static final String pwd = "koko0809";
    
    private DataSource dataSource;
    private QueryRunner queryRunner;
    private Connection conn;
    
    public BaseDAO() {
		try {
			dataSource = initDataSource();
			conn = dataSource.getConnection();
			queryRunner = new QueryRunner(dataSource);
		} catch (SQLException e) {
			e.printStackTrace();
		}
    	
    }
    
    private DataSource initDataSource() {
		MysqlConnectionPoolDataSource basicDs = new MysqlConnectionPoolDataSource();
		basicDs.setUser(usr); 
		basicDs.setPassword(pwd);
		basicDs.setServerName(servierName);
		basicDs.setDatabaseName(dateTableName);
		return basicDs;
	}
    
    protected QueryRunner getQueryRunner() {
    	return queryRunner;
    }
    
    protected Connection getConnection() {
    	return conn;
    }

    public void close() {
    	if (conn != null) {
    		DbUtils.closeQuietly(conn);
    	}
	}
    
    @Override
    protected void finalize() throws Throwable {
    	close();
    	super.finalize();
    }
}
